<template>
  <div>
    <el-upload :action="minioUploadUrl" list-type="picture" :multiple="false" :show-file-list="showFileList" :file-list="fileList" :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess" :on-preview="handlePreview">
      <el-button size="small" type="primary">点击上传</el-button>
      <div class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
    </el-upload>
    <el-dialog v-model="dataObj.dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="" />
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, ref, onBeforeMount } from 'vue'

const props = defineProps({
  value: {
    type: String
  },
  type: {
    type: String
  }
})

let state = props.value === null ? ref('') : ref(props.value)

let fileList = reactive([])

onBeforeMount(() => {
  if (state.value != null && state.value !== '') {
    fileList.push({
      name: state.value.substring(state.lastIndexOf('/') + 1),
      url: state.value
    })
  }
})

const showFileList = ref(false)

let dataObj = reactive({
  policy: '',
  signature: '',
  key: '',
  ossaccessKeyId: '',
  dir: '',
  host: '',
  dialogVisible: false
  // callback:'',
})

// const dialogImageUrl = ref('')
const useOss = ref(false)
const minioUploadUrl = ref('http://localhost:8080/minio/upload')

const emits = defineEmits(['uploadImage'])

function emitInput(val, type) {
  emits('uploadImage', val, type)
}
function handleRemove() {
  emitInput('')
}
function handlePreview() {
  dataObj.dialogVisible = true
}
function beforeUpload() {
  if (!useOss.value) {
    //不使用oss不需要获取策略
    return true
  }
}
function handleUploadSuccess(res, file) {
  showFileList.value = true
  let url = dataObj.host + '/' + dataObj.dir + '/' + file.name
  if (!useOss.value) {
    //不使用oss直接获取图片路径
    url = res.data.url
  }

  fileList.pop()
  fileList.push({ name: file.name, url: url })

  emitInput(fileList[0].url, props.type)
}
</script>
<style></style>
